﻿namespace CodeBetter.Extensions
{
   using System.Collections.Generic;

   /// <remarks>
   /// Most of these were contributted by DimeBrain:
   /// http://www.dimebrain.com/2008/07/idictionarys-mi.html
   /// </remarks>
   public static class IDictionaryExtensions
   {
      /// <summary>
      /// returns true if the value is in the dictionary
      /// </summary>      
      public static bool ContainsValue<K, V>(this IDictionary<K, V> instance, V value)
      {
         return instance.Exists(kvp => kvp.Value.Equals(value));
      }

      /// <summary>
      /// Gets the first key with the matching value. Returns true if the value is found, false if not.
      /// </summary>
      public static bool TryGetKey<K, V>(this IDictionary<K, V> instance, V value, out K key)
      {         
         foreach (var entry in instance)
         {
            if (entry.Value.Equals(value))
            {
               key = entry.Key;
               return true;
            }            
         }
         key = default(K);
         return false;
      }

      /// <summary>
      /// Gets all of th ekeys with the matching value. Returns true if the value is found, false if not.
      /// </summary>
      public static bool TryGetKeys<K, V>(this IDictionary<K, V> instance, V value, out K[] keys)
      {         
         var found = new List<K>();
         foreach (var entry in instance)
         {
            if (entry.Value.Equals(value))
            {
               found.Add(entry.Key);               
            }
         }
         keys = found.ToArray();
         return found.Count > 0;
      }
   }
}